//
//  PersonManagerViewController.m
//  WisdomZhuHai
//
//  Created by JasonLee on 15/1/30.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "PersonManagerViewController.h"
#import "PersonPhoneViewController.h"
#import "PersonViewController.h"
#import "TransforController.h"
#import "PasswordChangeViewController.h"
#import "PhoneVerifyViewController.h"

#define LOGINSTATUS @"loginStatus.plst"

@interface PersonManagerViewController ()<UITableViewDelegate, UITableViewDataSource, changePhoneProtocol>

@property (nonatomic, strong) UITableViewCell *cell_mobileBinding;
@property (nonatomic, strong) UITableView *view_table;

@end

@implementation PersonManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setFrame:CGRectMake(0, -65, 320, 613)];
    [self initView];
}

- (void)initView{
    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0];
    [self.view addSubview:view_navigationBar];
    
    self.view_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 65, 320, 503) style:UITableViewStyleGrouped];
    self.view_table.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view_table.bounds.size.width, 0.1)];
    self.view_table.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.view_table.bounds.size.width, 0)];
    self.view_table.backgroundColor = [UIColor colorWithRed:235/250.0 green:235/250.0 blue:235/250.0 alpha:1];
    self.title = @"帐号管理";
    self.view_table.delegate = self;
    self.view_table.dataSource = self;
    //    self.tableView.scrollEnabled = NO;
//    self.view_table.frame = CGRectMake(0, 65, 320, 503);
    [self.view addSubview:self.view_table];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 1;
        case 2:
            return 1;
        default:
            return 0;
            break;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    switch (indexPath.section) {
    //        case 0:
    //        case 1:
    //            return 45;
    //            break;
    //        case 2:
    //            return 50;
    //        default:
    //            break;
    //    }
    return 45;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
            if([ProtocolManager shareInstance].mobile == nil || [ProtocolManager shareInstance].mobile.length < 11){
                return @"尚未未绑定手机";
            }else{
                return @"已绑定手机";
            }
        case 1:
            return @"修改密码";
        default:
            return @"";
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = nil;
    switch (indexPath.section) {
        case 0:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                if([ProtocolManager shareInstance].mobile == nil || [ProtocolManager shareInstance].mobile.length < 11){
                    cell.textLabel.text = @"点击绑定";
                }else{
                    cell.textLabel.text = [ProtocolManager shareInstance].mobile;
                    cell.detailTextLabel.text = @"更换绑定";
                }
                self.cell_mobileBinding = cell;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            break;
        case 1:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            // Configure the cell...
            cell.textLabel.text = @"修改密码";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                UILabel *lb_logout = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
                lb_logout.textAlignment = UITextAlignmentCenter;
                lb_logout.textColor = [UIColor redColor];
                lb_logout.font = [UIFont fontWithName:@"Arial" size:16.0];
                lb_logout.text = @"退出登录";
                [cell addSubview:lb_logout];
            }
            break;
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                UILabel *lb_logout = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
                lb_logout.textAlignment = UITextAlignmentCenter;
                //                lb_logout.textColor = [UIColor redColor];
                lb_logout.font = [UIFont fontWithName:@"Arial" size:16.0];
                lb_logout.text = @"清除缓存";
                [cell addSubview:lb_logout];
            }
        default:
            break;
    }
    //    UIView *v = [[UIView alloc]init];
    //    v.backgroundColor = [UIColor clearColor];
    //    cell.backgroundView = v;
    //    cell.textLabel.backgroundColor = [UIColor clearColor];
    //    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
            [self gotoPhoneBindingViewController];
            break;
        case 1:
            [self gotoChangePassword];
            break;
        case 3:
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                               
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               NSLog(@"files :%d",[files count]);
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
            break;
        case 2:
            [self logoutAction];
            break;
        default:
            break;
    }
}

-(void)changePhoneAfterVerifying:(NSString *)phoneNumber{
    self.cell_mobileBinding.textLabel.text = phoneNumber;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 100001){
        if(buttonIndex == 1){
            NSLog(@"Log out.");
            //[self.delegate doLogOutWithConfirm];
//            [TransforController statusLoadingBar];
            [[ProtocolManager shareInstance]logout:self selector:@selector(getLogoutFinished:)];
        }
    }
}

- (void)gotoPhoneBindingViewController{
    PersonPhoneViewController *personPhoneController = [[PersonPhoneViewController alloc]init];
    NSLog(@"PhoneBind jump");
    personPhoneController.delegate = self;
    [self.navigationController pushViewController:personPhoneController animated:YES];
    //    [self presentViewController:personPhoneController animated:YES completion:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)logoutAction{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"确认退出?" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"退出", nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    alert.tag = 100001;
    [alert show]; //显示窗口
}

- (void)getLogoutFinished:(NSDictionary *)dic{
    if(dic == nil){
        [[Common shareInstance] showAlertViewWithTitle:nil text:@"连接服务器失败" dismissTime:0.8];
        return;
    }
    ThirdViewController *temp_thirdView = [TransforController sharedInstanceOfThirdViewController];
    [temp_thirdView changeStatusAfterLogin:0];
    [[Common shareInstance] showAlertViewWithTitle:nil text:@"退出成功" dismissTime:0.8];
    [ProtocolManager shareInstance].sid = nil;
    [ProtocolManager shareInstance].userId = -1;
    [ProtocolManager shareInstance].loginName = nil;
    [ProtocolManager shareInstance].mobile = nil;
    [ProtocolManager shareInstance].username = nil;
    NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
    [savingDic setValue:@"0000" forKey:@"LoginStatus"];
    [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];

}

- (void)gotoChangePassword{
    PasswordChangeViewController *instance_passwordChange = [[PasswordChangeViewController alloc]init];
    instance_passwordChange.hidesBottomBarWhenPushed = YES;
    instance_passwordChange.isChangeWithPhone = NO;
    [self.navigationController pushViewController:instance_passwordChange animated:YES];
}


@end
